package logic

import (
	"context"
	"encoding/json"
	"github.com/zeromicro/go-zero/core/logx"
	"goods-manager/cache"
	"goods-manager/goodrpc/goodrpc"
	"goods-manager/goodrpc/internal/svc"
	"goods-manager/model"
	"time"
)

type GoodListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodListLogic {
	return &GoodListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GoodListLogic) GoodList(in *goodrpc.GoodListRequest) (*goodrpc.GoodListResponse, error) {
	// todo: add your logic here and delete this line
	var data []model.Good
	redis_list_key := "list_key"
	result, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()
	if result == "" {
		model.DB.Find(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &data)
	}
	goods := []*goodrpc.GoodList{}
	return &goodrpc.GoodListResponse{
		List: goods,
	}, nil
}
